import axios from 'axios';
import FormData from 'form-data';
import config from '../config/index.js';
import { checkUserPermission } from './authService.js';

export async function handleFileUpload(req, res) {
  const { appId, appuserId, platform = "sgj_teacher_weapp" } = req.body;
  
  // 验证用户权限
  const authResult = await checkUserPermission(appId, appuserId, platform);
  if (!authResult.success) {
    res.status(403).send(authResult.message);
    return;
  }

  const APIkey = authResult.APIkey;
  const file = req.file;

  const formData = new FormData();
  formData.append("file", Buffer.from(file.buffer), {
    filename: file.originalname,
    contentType: file.mimetype,
  });
  formData.append("user", `${platform}_${appuserId}`);

  try {
    const response = await axios.post(
      `${config.server.dify}/files/upload`,
      formData,
      {
        headers: {
          Authorization: `Bearer ${APIkey}`,
          ...formData.getHeaders(),
        },
      }
    );

    res.status(response.status).send(response.data);
  } catch (error) {
    console.error("文件上传错误:", error);
    res.status(500).send(error.message);
  }
}
